//
//  ZCfollowVC.m
//  zctx
//
//  Created by apple on 16/1/4.
//  Copyright © 2016年 sanliang. All rights reserved.
//

#import "ZCfollowVC.h"
#import "ZCSearchQualifiedCell.h"
#import "ZCSearchInvolvedCell.h"
#import "ZCSearchSamplingCell.h"
#import "ZCSearchQualifiedOKCell.h"

#import "ZCfollowModelContent.h"
#import "ZCInvolvedDetailsVC.h"

@interface ZCfollowVC ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic,assign)NSInteger offset; //页数
@property (nonatomic, strong) NSMutableArray *arrResult; //搜索结果数组

@property BOOL isnothing;
@end

@implementation ZCfollowVC
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"ZCfollowVC"];
    [MTA trackPageViewBegin:@"ZCfollowVC"];
    self.tabBarController.hidesBottomBarWhenPushed = YES;

}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"ZCfollowVC"];
    [MTA trackPageViewEnd:@"ZCfollowVC"];
    self.tabBarController.hidesBottomBarWhenPushed = NO;
    
}

-(void)updateRequest{
    if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus >0) {
        self.bannerView.hidden = YES;
    }
    [self requestMainList];
}

- (void)viewDidLoad {
    [super viewDidLoad];
//    self.edgesForExtendedLayout = UIRectEdgeNone;
    //AF 开启监听网络状态
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    self.navigationItem.title = @"关注的项目";
    self.isnothing = NO;
    self.offset = 0;
    self.arrResult = [NSMutableArray array];
//    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//        [self requestMainList];
//    });
    

    [self initnavegation];
    [self initTableView];
    [self requestMainList];
    self.tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    [self.tableView registerNib:[UINib nibWithNibName:@"ZCSearchQualifiedCell" bundle:nil] forCellReuseIdentifier:@"SearchQualified"];
    [self.tableView registerNib:[UINib nibWithNibName:@"ZCSearchInvolvedCell" bundle:nil] forCellReuseIdentifier:@"SearchInvolved"];
    [self.tableView registerNib:[UINib nibWithNibName:@"ZCSearchSamplingCell" bundle:nil] forCellReuseIdentifier:@"SearchSampling"];
    [self.tableView registerNib:[UINib nibWithNibName:@"ZCSearchQualifiedOKCell" bundle:nil] forCellReuseIdentifier:@"qualifiedOKcell"];
 
    self.tableView.mj_footer = [MJDIYFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];

}

#pragma mark 导航栏
-(void)initnavegation{
    
    UIButton * leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    leftButton.frame = CGRectMake(0, 0, 19, 36);
    [leftButton setImage:[UIImage imageNamed:@"navigation_back"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(backButtonPressed) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * barButtonItem_leftNavBar = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    self.navigationItem.leftBarButtonItem =barButtonItem_leftNavBar;
}
-(void)backButtonPressed{

    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark 加载更多
-(void)loadMoreData{
    //上拉加载
    _offset = _offset+1;
    [self requestMainList];
    
}
#pragma mark - request 网络请求

- (void)requestMainList {
    if (_offset==0) {
        [GMDCircleLoader setOnView:self.view withTitle:@"努力加载中..." animated:YES];
    }
    [NetworkManager requestIndexCollectionFoundingsWithMid:UserModel.mid password:UserModel.password pagecount:[NSString stringWithFormat:@"%ld",(long)_offset] success:^(NSDictionary *dictResponse) {
        [GMDCircleLoader hideFromView:self.view animated:YES];
        [self.tableView.mj_footer endRefreshing];
        if ([[dictResponse objectForKey:@"content"] isKindOfClass:[NSArray class]]) {
            NSArray *array = (NSArray  *)[dictResponse objectForKey:@"content"];
            
            if (_offset==0) {
                
                if (array.count>0) {
                    self.isnothing = NO;
                }else{
                    self.isnothing = YES;
                }
            }
            if (array.count>0) {
                [self.arrResult addObjectsFromArray:array];;
                [self.tableView reloadData];
            }
        }else{
            self.isnothing = YES;
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
            [self.tableView reloadData];
        }
    } failure:^(NSError *error) {
        [GMDCircleLoader hideFromView:self.view animated:YES];
        if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == 0) {
            self.bannerView.hidden = NO;
        }
    }];
}


-(void)initTableView{
    _tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorColor = RGB(236, 237, 238);
    _tableView.backgroundColor = [UIColor colorWithHexString:@"#fafcfb"];
    [self.view addSubview:_tableView];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view).with.insets(UIEdgeInsetsMake(0,0,0,0));
    }];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.arrResult.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ZCfollowModelContent *model;
    if (self.arrResult.count>0) {
        model = [ZCfollowModelContent modelObjectWithDictionary:self.arrResult[indexPath.row]];
    }
    NSString *nameStr = [NSString stringWithFormat:@"%@",model.pjname];
    NSString *batchStr = [NSString stringWithFormat:@"%@",model.batch];
    NSString *testing_resultStr = [NSString stringWithFormat:@"%@",model.testing_result];

    if ([model.result isEqualToString:@"1"] ||[model.result isEqualToString:@"2"]) {
        if ([model.result isEqualToString:@"1"]) {
            static NSString *cellIndentity = @"qualifiedOKcell";
            ZCSearchQualifiedOKCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndentity];
            if (!cell) {
                cell = [[ZCSearchQualifiedOKCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndentity];
            }
            cell.titleLable.text = nameStr;
            cell.tiemLable.text = batchStr;
            cell.ImgView.image = [UIImage imageNamed:@"search_yes"];
            return cell;
        }else{
            static NSString *cellIndentity = @"SearchQualified";
            ZCSearchQualifiedCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndentity];
            if (!cell) {
                cell = [[ZCSearchQualifiedCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndentity];
            }
            cell.titleLable.text = nameStr;
            cell.pihaoLable.text = batchStr;
            cell.timeLable.text = testing_resultStr;
            cell.timeLable.textColor = [UIColor redColor];
            cell.iconImgView.image = [UIImage imageNamed:@"search_no"];
            return cell;
        }
    }else{
        if ([model.state isEqualToString:@"1"]||[model.state isEqualToString:@"0"]) {
            static NSString *cellid =@"SearchInvolved";
            ZCSearchInvolvedCell *cell = [tableView dequeueReusableCellWithIdentifier:cellid];
            if (cell == nil) {
                cell = [[ZCSearchInvolvedCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellid];
            }
            cell.Model = model;
            return cell;
        }
        else
        {// 0 审核中  2 抽样中 3完成 4 异常
            static NSString *cellid =@"SearchSampling";
            ZCSearchSamplingCell *cell = [tableView dequeueReusableCellWithIdentifier:cellid];
            if (cell == nil) {
                cell = [[ZCSearchSamplingCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellid];
            }
            cell.Model = model;
            return cell;
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 92;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *model;
    if (self.arrResult.count>0) {
        model = (NSDictionary *)self.arrResult[indexPath.row];
    }
    NSString *str = [NSString stringWithFormat:@"%@",[model objectForKey:@"for_id"]];
    
    ZCInvolvedDetailsVC *invoVC = [[ZCInvolvedDetailsVC alloc]init];
    invoVC.hidesBottomBarWhenPushed = YES;
    invoVC.pid = str;
    [self.navigationController pushViewController:invoVC animated:YES];
    
    [self performSelector:@selector(unselectCell:) withObject:nil afterDelay:0.3];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.0001;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    if (self.isnothing == NO) {
        UIView *footView = [[UIView alloc]init];
        footView.backgroundColor = [UIColor colorWithHexString:@"#fafcfb"];
        return footView;
    }else{
        
        UIView *footView = [[UIView alloc]initWithFrame:CGRectMake(0, 0,SCREEN_WIDTH,400)];
        footView.backgroundColor = [UIColor colorWithHexString:@"#fafcfb"];
        
        UIImageView*redImg = [[UIImageView alloc]init];
        [footView addSubview:redImg];
        [redImg makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(footView.top).with.offset(0.255 * SCREEN_HEIGHT);
            make.centerX.equalTo (footView.centerX).with.offset(0);
            make.height.mas_equalTo(100);
            make.width.mas_equalTo(100);
        }];
        [redImg setImage:[UIImage imageNamed:@"me_follow_no"]];
        
        UILabel*redLable = [[UILabel alloc]init];
        [footView addSubview:redLable];
        [redLable makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(redImg.bottom).with.offset(23);
            make.centerX.equalTo (footView.centerX).with.offset(0);
            make.height.mas_equalTo(21);
            make.width.mas_equalTo(150);
        }];
        redLable.textAlignment = NSTextAlignmentCenter;
        redLable.text = @"无关注的项目";
        redLable.textColor = [UIColor colorWithHexString:@"#d2d2d2"];
        redLable.font = [UIFont systemFontOfSize:16];
        return footView;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (self.isnothing ==NO) {
        return 0.001;
    }else{
        return 400;
    }
}

-(void)unselectCell:(id)sender{
    [self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow] animated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
